@extenshi/pay 0.9.0 → 0.12.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.
Files changed (74) hide show
  1. package/README.md +138 -17
  2. package/dist/api/mock.d.ts +4 -0
  3. package/dist/api/mock.d.ts.map +1 -1
  4. package/dist/api/pay-api.d.ts +9 -4
  5. package/dist/api/pay-api.d.ts.map +1 -1
  6. package/dist/core/config.d.ts.map +1 -1
  7. package/dist/core/extenshi-pay.d.ts +60 -5
  8. package/dist/core/extenshi-pay.d.ts.map +1 -1
  9. package/dist/core/index.d.ts +3 -1
  10. package/dist/core/index.d.ts.map +1 -1
  11. package/dist/core/storage.d.ts +6 -0
  12. package/dist/core/storage.d.ts.map +1 -1
  13. package/dist/core.d.mts +271 -26
  14. package/dist/core.d.ts +271 -26
  15. package/dist/core.js +589 -49
  16. package/dist/core.js.map +1 -1
  17. package/dist/core.mjs +584 -50
  18. package/dist/core.mjs.map +1 -1
  19. package/dist/extenshi-pay-lite.js +577 -49
  20. package/dist/extenshi-pay-lite.js.map +1 -1
  21. package/dist/extenshi-pay-lite.min.js +3 -3
  22. package/dist/extenshi-pay-lite.min.js.map +1 -1
  23. package/dist/extenshi-pay-lite.mjs +577 -49
  24. package/dist/extenshi-pay-lite.mjs.map +1 -1
  25. package/dist/extenshi-pay.cjs.js +694 -61
  26. package/dist/extenshi-pay.cjs.js.map +1 -1
  27. package/dist/extenshi-pay.d.ts +11 -1
  28. package/dist/extenshi-pay.d.ts.map +1 -1
  29. package/dist/extenshi-pay.js +694 -61
  30. package/dist/extenshi-pay.js.map +1 -1
  31. package/dist/extenshi-pay.min.js +3 -3
  32. package/dist/extenshi-pay.min.js.map +1 -1
  33. package/dist/extenshi-pay.min.mjs +3 -3
  34. package/dist/extenshi-pay.min.mjs.map +1 -1
  35. package/dist/extenshi-pay.mjs +689 -62
  36. package/dist/extenshi-pay.mjs.map +1 -1
  37. package/dist/index.d.mts +288 -26
  38. package/dist/index.d.ts +288 -26
  39. package/dist/lite.d.mts +214 -13
  40. package/dist/lite.d.ts +214 -13
  41. package/dist/lite.d.ts.map +1 -1
  42. package/dist/payment/cloud-backup.d.ts +35 -0
  43. package/dist/payment/cloud-backup.d.ts.map +1 -0
  44. package/dist/payment/entitlement.d.ts +21 -5
  45. package/dist/payment/entitlement.d.ts.map +1 -1
  46. package/dist/payment/recovery.d.ts +4 -2
  47. package/dist/payment/recovery.d.ts.map +1 -1
  48. package/dist/payment/signature.d.ts +29 -3
  49. package/dist/payment/signature.d.ts.map +1 -1
  50. package/dist/payment/trial.d.ts +55 -0
  51. package/dist/payment/trial.d.ts.map +1 -0
  52. package/dist/paywall/i18n.d.ts +3 -0
  53. package/dist/paywall/i18n.d.ts.map +1 -1
  54. package/dist/paywall/renderer.d.ts +7 -0
  55. package/dist/paywall/renderer.d.ts.map +1 -1
  56. package/dist/paywall.d.mts +7 -0
  57. package/dist/paywall.d.ts +7 -0
  58. package/dist/paywall.js +54 -14
  59. package/dist/paywall.js.map +1 -1
  60. package/dist/paywall.mjs +54 -14
  61. package/dist/paywall.mjs.map +1 -1
  62. package/dist/types/config.d.ts +27 -1
  63. package/dist/types/config.d.ts.map +1 -1
  64. package/dist/types/contract.d.ts +36 -0
  65. package/dist/types/contract.d.ts.map +1 -1
  66. package/dist/types/entitlement.d.ts +39 -1
  67. package/dist/types/entitlement.d.ts.map +1 -1
  68. package/dist/types/events.d.ts +5 -1
  69. package/dist/types/events.d.ts.map +1 -1
  70. package/dist/types/paywall.d.ts +10 -0
  71. package/dist/types/paywall.d.ts.map +1 -1
  72. package/dist/version.d.ts +1 -1
  73. package/dist/version.d.ts.map +1 -1
  74. package/package.json +3 -2
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * ExtenshiPay SDK v0.9.0
2
+ * ExtenshiPay SDK v0.12.0
3
3
  * (c) 2026 Extenshi.io
4
4
  * Released under the MIT License.
5
- * commit bd166bf9b687f60e965d03acec7a648b42226652 · built by `rollup -c`
5
+ * commit 7f4b4e98165b3c8eb11e100b3855fee1ade7aaab · built by `rollup -c`
6
6
  */
7
7
  (function (global, factory) {
8
8
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
@@ -35,6 +35,8 @@
35
35
  function isPayPublishableKey(value) {
36
36
  return typeof value === 'string' && PUBLISHABLE_KEY_RE.test(value);
37
37
  }
38
+ // Outside the seller SKU grammar. Issued only in a signed projection, never in the sales ledger.
39
+ const PAY_REGIONAL_ACCESS_SKU = '@regional-free';
38
40
  /**
39
41
  * Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA
40
42
  * digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The
@@ -73,6 +75,8 @@
73
75
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
74
76
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
75
77
  }
78
+ /** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
79
+ const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
76
80
 
77
81
  const ERROR_CODES = {
78
82
  INVALID_CONFIG: 'INVALID_CONFIG',
@@ -144,7 +148,7 @@
144
148
  * developed with no backend: offers and entitlements come from `mockData`, a
145
149
  * mock checkout completes after `claimAfterPolls` polls and grants the SKU.
146
150
  */
147
- const DAY_MS = 24 * 60 * 60 * 1000;
151
+ const DAY_MS$1 = 24 * 60 * 60 * 1000;
148
152
  /** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
149
153
  function mockConsent(value) {
150
154
  const consent = value;
@@ -162,6 +166,10 @@
162
166
  this.claimAfterPolls = data.claimAfterPolls ?? 1;
163
167
  this.withdrawalWaiver =
164
168
  data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
169
+ this.seller = data.seller;
170
+ this.trial = null;
171
+ if (data.trial)
172
+ this.setTrial(data.trial.days, data.trial.startedAt);
165
173
  }
166
174
  async call(procedure, _kind, input) {
167
175
  switch (procedure) {
@@ -183,6 +191,14 @@
183
191
  setEntitlements(items) {
184
192
  this.entitlements = [...items];
185
193
  }
194
+ /** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
195
+ setTrial(days, startedAt = new Date().toISOString()) {
196
+ const start = Date.parse(startedAt);
197
+ this.trial =
198
+ days === null || !Number.isFinite(start)
199
+ ? null
200
+ : { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
201
+ }
186
202
  cancelSession(sessionId) {
187
203
  const session = this.sessions.get(sessionId);
188
204
  if (session)
@@ -202,6 +218,7 @@
202
218
  offers: [...this.offers],
203
219
  entitlementPublicKey: null,
204
220
  withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
221
+ ...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
205
222
  };
206
223
  }
207
224
  createCheckout(sku, withdrawalWaiver) {
@@ -239,7 +256,7 @@
239
256
  grant(sku) {
240
257
  const offer = this.offers.find((o) => o.sku === sku);
241
258
  const expiresAt = offer?.kind === 'subscription'
242
- ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
259
+ ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
243
260
  : null;
244
261
  this.entitlements = [
245
262
  ...this.entitlements.filter((item) => item.sku !== sku),
@@ -261,6 +278,7 @@
261
278
  endUserRef,
262
279
  entitlements: [...this.entitlements],
263
280
  issuedAt: new Date().toISOString(),
281
+ ...(this.trial ? { trial: { ...this.trial } } : {}),
264
282
  },
265
283
  signature: null,
266
284
  alg: null,
@@ -274,12 +292,17 @@
274
292
  this.transport = transport;
275
293
  this.publishableKey = publishableKey;
276
294
  }
277
- /** `locale` opens the hosted recovery page (and its email) in the user's language. */
278
- createRestoreSession(claimChallenge, locale) {
295
+ /**
296
+ * `locale` opens the hosted recovery page (and its email) in the user's language.
297
+ * `purpose` is sent only for `storage`: a plain restore keeps the request older
298
+ * BFFs know, and their non-strict zod input strips the key anyway.
299
+ */
300
+ createRestoreSession(claimChallenge, locale, purpose) {
279
301
  return this.transport.call('pay.createRestoreSession', 'mutation', {
280
302
  publishableKey: this.publishableKey,
281
303
  claimChallenge,
282
304
  ...(locale ? { locale } : {}),
305
+ ...(purpose === 'storage' ? { purpose } : {}),
283
306
  });
284
307
  }
285
308
  claimRestoreSession(sessionId, claimSecret) {
@@ -318,10 +341,12 @@
318
341
  endUserRef,
319
342
  });
320
343
  }
321
- getEntitlement(endUserRef) {
344
+ /** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
345
+ getEntitlement(endUserRef, trialStartedHint) {
322
346
  return this.transport.call('pay.getEntitlement', 'query', {
323
347
  publishableKey: this.publishableKey,
324
348
  endUserRef,
349
+ ...(trialStartedHint ? { trialStartedHint } : {}),
325
350
  });
326
351
  }
327
352
  getPortalUrl(endUserRef, customerId, locale) {
@@ -719,6 +744,118 @@
719
744
  openInNewTab: openInNewTab
720
745
  });
721
746
 
747
+ /**
748
+ * Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
749
+ * token: only a verified restore claim issues it; this module keeps it in the
750
+ * SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
751
+ * through `cloudBackupToken()`. The token is never logged and never answered to
752
+ * a content script: route those calls to the background.
753
+ */
754
+ const REQUEST_TIMEOUT_MS = 10000;
755
+ /** True in a content script, where the token must not be handed out. */
756
+ function inContentScript() {
757
+ const g = globalThis;
758
+ return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
759
+ }
760
+ class CloudBackup {
761
+ constructor(options) {
762
+ this.options = options;
763
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
764
+ }
765
+ get storageKey() {
766
+ return `extenshi-pay:${this.options.publishableKey}:storageToken`;
767
+ }
768
+ /** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
769
+ async accept(grant) {
770
+ if (!grant || typeof grant !== 'object')
771
+ return undefined;
772
+ try {
773
+ if (grant.state === 'granted') {
774
+ if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
775
+ return undefined;
776
+ await this.options.storage.set(this.storageKey, grant.token);
777
+ return 'on';
778
+ }
779
+ if (grant.state === 'unavailable') {
780
+ await this.options.storage.remove(this.storageKey);
781
+ return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
782
+ }
783
+ }
784
+ catch {
785
+ logger.warn('cloud backup state could not be saved');
786
+ }
787
+ return undefined;
788
+ }
789
+ async token() {
790
+ this.assertTrustedContext();
791
+ const value = await this.options.storage.get(this.storageKey);
792
+ return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
793
+ }
794
+ /** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
795
+ async disable() {
796
+ const token = await this.token();
797
+ if (!token)
798
+ return;
799
+ if (!this.options.mock) {
800
+ const status = await this.request('/v1/storage/grant', token);
801
+ if (status !== 401)
802
+ this.throwUnlessOk(status);
803
+ }
804
+ await this.options.storage.remove(this.storageKey);
805
+ }
806
+ /** Deletes the buyer's cloud copy and turns the backup off on every device. */
807
+ async delete() {
808
+ const token = await this.token();
809
+ if (!token)
810
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
811
+ if (!this.options.mock) {
812
+ const status = await this.request('/v1/storage/data', token);
813
+ if (status === 401) {
814
+ // The server no longer accepts this token, so it is useless here; the copy was not deleted.
815
+ await this.options.storage.remove(this.storageKey);
816
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on the server; turn it on again to delete the cloud copy', { httpStatus: 401 });
817
+ }
818
+ this.throwUnlessOk(status);
819
+ }
820
+ await this.options.storage.remove(this.storageKey);
821
+ }
822
+ assertTrustedContext() {
823
+ if (inContentScript())
824
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
825
+ }
826
+ throwUnlessOk(status) {
827
+ if (status >= 200 && status < 300)
828
+ return;
829
+ if (status === 429)
830
+ throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
831
+ if (status >= 500)
832
+ throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
833
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
834
+ }
835
+ async request(path, token) {
836
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
837
+ const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
838
+ try {
839
+ const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
840
+ method: 'DELETE',
841
+ headers: { Authorization: `Bearer ${token}` },
842
+ credentials: 'omit',
843
+ signal: controller?.signal,
844
+ });
845
+ return response.status;
846
+ }
847
+ catch (error) {
848
+ if (controller?.signal.aborted)
849
+ throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
850
+ throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
851
+ }
852
+ finally {
853
+ if (timer !== null)
854
+ clearTimeout(timer);
855
+ }
856
+ }
857
+ }
858
+
722
859
  /** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
723
860
  const LIVE_STATUSES = new Set(['active', 'grace']);
724
861
  function isLive(item) {
@@ -773,9 +910,17 @@
773
910
  /**
774
911
  * Ed25519 verification of the entitlement projection.
775
912
  *
776
- * Tamper resistance, not DRM. Trust comes from the developer's bundled key or
777
- * a key fetched over HTTPS, never from editable extension storage. Callers must
778
- * deny access for both invalid and unverified envelopes outside explicit mocks.
913
+ * Tamper resistance, not DRM. Callers must deny access for both invalid and
914
+ * unverified envelopes outside explicit mocks.
915
+ *
916
+ * Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
917
+ * 1. the key the server returned over HTTPS in this session;
918
+ * 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
919
+ * verification without a round-trip: a key read from extension storage is then never used;
920
+ * 3. without a bundled key, the server key saved in `storage.local` next to the
921
+ * license cache, so a restart with no network can still verify the cache.
922
+ * When none of them verifies an envelope the server is asked for its current key once
923
+ * (a rotated key), and that answer decides.
779
924
  */
780
925
  function base64ToBytes(base64) {
781
926
  const binary = atob(base64);
@@ -810,6 +955,140 @@
810
955
  return 'invalid';
811
956
  }
812
957
  }
958
+ const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
959
+ /**
960
+ * `invalid` only when the server's current key was checked too (or the envelope carries no
961
+ * signature at all). A mismatch against known keys while the server is unreachable is
962
+ * `unverified`: it may be a rotated key, and no paid access is granted either way.
963
+ */
964
+ async function verifyWithKeys(envelope, source) {
965
+ if (!envelope.signature || envelope.alg !== 'ed25519')
966
+ return { verdict: 'invalid', key: null };
967
+ let known = [];
968
+ try {
969
+ known = await source.known();
970
+ }
971
+ catch {
972
+ known = [];
973
+ }
974
+ let mismatch = false;
975
+ for (const key of known) {
976
+ const verdict = await verifyEntitlementSignature(envelope, key);
977
+ if (verdict === 'valid')
978
+ return { verdict, key };
979
+ if (verdict === 'invalid')
980
+ mismatch = true;
981
+ }
982
+ let current;
983
+ try {
984
+ current = await source.fetchCurrent();
985
+ }
986
+ catch {
987
+ return { verdict: 'unverified', key: null };
988
+ }
989
+ if (current && !known.includes(current)) {
990
+ const verdict = await verifyEntitlementSignature(envelope, current);
991
+ return { verdict, key: verdict === 'valid' ? current : null };
992
+ }
993
+ return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
994
+ }
995
+
996
+ /**
997
+ * The free trial an application configures on the server (`trialDays`).
998
+ *
999
+ * The server starts one clock per installation at its first license read and
1000
+ * signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
1001
+ * the verified license like paid access does: no start date in extension
1002
+ * storage, nothing a device clock or a storage edit can move. Offline, the
1003
+ * cached license answers for up to 48 hours.
1004
+ *
1005
+ * `trial:ending` / `trial:ended` fire once per installation and trial (the
1006
+ * marker is kept in the SDK's storage), and not while the user has paid
1007
+ * access. Render state from `getTrial()`; the events are one-time notices.
1008
+ */
1009
+ const DAY_MS = 24 * 60 * 60 * 1000;
1010
+ /** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
1011
+ const MAX_TIMER_MS$1 = DAY_MS;
1012
+ /** The trial as of `clock`, or null when the license carries none (or a malformed one). */
1013
+ function trialState(trial, clock) {
1014
+ if (!trial)
1015
+ return null;
1016
+ const startedAt = Date.parse(trial.startedAt);
1017
+ const endsAt = Date.parse(trial.endsAt);
1018
+ if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
1019
+ return null;
1020
+ // The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
1021
+ const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
1022
+ const left = endsAt - now;
1023
+ return {
1024
+ active: left > 0 && clock.checked,
1025
+ startedAt: trial.startedAt,
1026
+ endsAt: trial.endsAt,
1027
+ daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
1028
+ requiresOnlineCheck: left > 0 && !clock.checked,
1029
+ };
1030
+ }
1031
+ class TrialNotifier {
1032
+ constructor(options) {
1033
+ this.options = options;
1034
+ this.timer = null;
1035
+ this.running = false;
1036
+ this.pending = Promise.resolve();
1037
+ }
1038
+ start() {
1039
+ this.running = true;
1040
+ void this.evaluate();
1041
+ }
1042
+ stop() {
1043
+ this.running = false;
1044
+ this.clearTimer();
1045
+ }
1046
+ /** Checks the held license; serialized, so two refreshes never send one event twice. */
1047
+ evaluate() {
1048
+ this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
1049
+ return this.pending;
1050
+ }
1051
+ async check() {
1052
+ if (!this.running)
1053
+ return;
1054
+ this.clearTimer();
1055
+ const trial = this.options.getTrial();
1056
+ if (!trial)
1057
+ return;
1058
+ const now = this.options.now();
1059
+ const endsAt = Date.parse(trial.endsAt);
1060
+ const endingAt = endsAt - this.options.endingDays * DAY_MS;
1061
+ const event = trial.daysLeft === 0
1062
+ ? 'trial:ended'
1063
+ : trial.active && this.options.endingDays > 0 && now >= endingAt
1064
+ ? 'trial:ending'
1065
+ : null;
1066
+ if (event && !this.options.hasPaidAccess())
1067
+ await this.send(event, trial);
1068
+ if (!this.running || trial.daysLeft === 0)
1069
+ return;
1070
+ const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
1071
+ this.timer = setTimeout(() => {
1072
+ this.timer = null;
1073
+ void this.evaluate();
1074
+ }, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
1075
+ }
1076
+ async send(event, trial) {
1077
+ const id = `${trial.startedAt}|${trial.endsAt}`;
1078
+ const field = event === 'trial:ended' ? 'ended' : 'ending';
1079
+ const stored = (await this.options.storage.get(this.options.storageKey));
1080
+ const sent = stored && typeof stored === 'object' ? stored : {};
1081
+ if (sent[field] === id || !this.running)
1082
+ return;
1083
+ await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
1084
+ this.options.emit(event, trial);
1085
+ }
1086
+ clearTimer() {
1087
+ if (this.timer !== null)
1088
+ clearTimeout(this.timer);
1089
+ this.timer = null;
1090
+ }
1091
+ }
813
1092
 
814
1093
  /**
815
1094
  * Entitlement cache + refresh.
@@ -817,13 +1096,18 @@
817
1096
  * The cached envelope is a cache OF the server projection, never a second
818
1097
  * source of truth: it is verified when stored and re-verified on load (once
819
1098
  * the project's public key is known), served without a round-trip while the
820
- * TTL holds, served for up to 48 hours after signed issuance when the network is down, and expired
1099
+ * TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
821
1100
  * locally by `expiresAt`. Background refresh polls at most every 15 minutes
822
1101
  * and backs off exponentially on errors.
823
1102
  */
824
1103
  const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
825
1104
  const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
1105
+ /** Offline allowance when the signed license names none (older servers and caches). */
826
1106
  const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
1107
+ /** Ceiling for a signed `offlineSeconds`. */
1108
+ const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
1109
+ /** `setTimeout` fires at once past this delay. */
1110
+ const MAX_TIMER_MS = 2 ** 31 - 1;
827
1111
  // Allow small server/client clock skew without granting more than the signed age limit.
828
1112
  const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
829
1113
  const CACHE_VERSION = 1;
@@ -842,6 +1126,8 @@
842
1126
  this.options = options;
843
1127
  this.held = null;
844
1128
  this.inflight = null;
1129
+ /** Device clock against the server's at the last license check; null within 5 minutes. */
1130
+ this.clockSkew = null;
845
1131
  this.timer = null;
846
1132
  this.refreshGeneration = 0;
847
1133
  this.deadlineTimer = null;
@@ -883,8 +1169,10 @@
883
1169
  envelope: JSON.parse(JSON.stringify(record.envelope)),
884
1170
  fetchedAt: record.fetchedAt,
885
1171
  verified: false,
1172
+ key: null,
886
1173
  source: this.source === 'mock' ? 'mock' : 'cache',
887
1174
  };
1175
+ this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
888
1176
  this.lastFingerprint = this.fingerprint();
889
1177
  return this.snapshot();
890
1178
  }
@@ -895,8 +1183,7 @@
895
1183
  if (this.source === 'mock')
896
1184
  return;
897
1185
  const held = this.held;
898
- const key = await this.safePublicKey();
899
- const verdict = await verifyEntitlementSignature(held.envelope, key);
1186
+ const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
900
1187
  if (held !== this.held)
901
1188
  return;
902
1189
  if (verdict === 'invalid') {
@@ -905,19 +1192,39 @@
905
1192
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
906
1193
  }
907
1194
  held.verified = verdict === 'valid';
1195
+ held.key = key;
908
1196
  if (!held.verified) {
909
1197
  throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
910
1198
  }
911
1199
  this.scheduleDeadline();
912
1200
  }
1201
+ /** The key the held license was verified with; null when there is none or it is unverified. */
1202
+ get verifiedKey() {
1203
+ return this.held?.verified ? this.held.key : null;
1204
+ }
913
1205
  getCached() {
914
1206
  return this.held ? this.snapshot() : null;
915
1207
  }
1208
+ /** The server trial in the held license; null without one, or while the license is unverified. */
1209
+ getTrial() {
1210
+ const held = this.held;
1211
+ if (!held || (this.source !== 'mock' && !held.verified))
1212
+ return null;
1213
+ const now = this.now();
1214
+ const issuedAt = Date.parse(held.envelope.payload.issuedAt);
1215
+ return trialState(held.envelope.payload.trial, {
1216
+ now,
1217
+ issuedAt,
1218
+ // The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
1219
+ checked: this.source === 'mock' ||
1220
+ (now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
1221
+ });
1222
+ }
916
1223
  isFresh() {
917
1224
  return (this.held !== null &&
918
1225
  (this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
919
1226
  this.now() >= this.held.fetchedAt &&
920
- this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS));
1227
+ this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
921
1228
  }
922
1229
  async get(options = {}) {
923
1230
  if (!options.force && this.isFresh())
@@ -932,7 +1239,7 @@
932
1239
  logger.debug('serving cached entitlement after refresh failure', err.code);
933
1240
  return this.snapshot();
934
1241
  }
935
- return EMPTY_ENTITLEMENT;
1242
+ return this.snapshot();
936
1243
  }
937
1244
  }
938
1245
  /** Fetches the projection from the backend, verifies and stores it. */
@@ -940,7 +1247,8 @@
940
1247
  if (!this.inflight) {
941
1248
  this.inflight = (async () => {
942
1249
  const endUserRef = await this.options.getEndUserRef();
943
- const envelope = await this.options.api.getEntitlement(endUserRef);
1250
+ const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
1251
+ const envelope = await this.options.api.getEntitlement(endUserRef, hint);
944
1252
  return this.accept(envelope, this.source);
945
1253
  })().finally(() => {
946
1254
  this.inflight = null;
@@ -962,9 +1270,9 @@
962
1270
  if (envelope.payload.endUserRef !== endUserRef) {
963
1271
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
964
1272
  }
965
- const verdict = this.source === 'mock'
966
- ? 'unverified'
967
- : await verifyEntitlementSignature(envelope, await this.safePublicKey());
1273
+ const { verdict, key } = this.source === 'mock'
1274
+ ? { verdict: 'unverified', key: null }
1275
+ : await verifyWithKeys(envelope, this.options.keys);
968
1276
  if (verdict === 'invalid') {
969
1277
  await this.discard();
970
1278
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
@@ -974,15 +1282,19 @@
974
1282
  }
975
1283
  const fetchedAt = this.now();
976
1284
  const issuedAt = Date.parse(envelope.payload.issuedAt);
1285
+ // A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
1286
+ if (this.source !== 'mock')
1287
+ this.measureClockSkew(fetchedAt, issuedAt);
977
1288
  if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
978
1289
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
979
1290
  }
980
- this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
1291
+ this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
981
1292
  const record = { v: CACHE_VERSION, envelope, fetchedAt };
982
1293
  await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
983
1294
  this.backoffMs = 0;
984
1295
  this.scheduleDeadline();
985
1296
  this.notifyIfChanged();
1297
+ this.options.onAccepted?.();
986
1298
  return this.snapshot();
987
1299
  }
988
1300
  /** Drain an older installation refresh before changing identity. */
@@ -1036,7 +1348,7 @@
1036
1348
  this.deadlineTimer = null;
1037
1349
  this.notifyIfChanged();
1038
1350
  this.scheduleDeadline();
1039
- }, remaining);
1351
+ }, Math.min(remaining, MAX_TIMER_MS));
1040
1352
  }
1041
1353
  schedule(delayMs) {
1042
1354
  const generation = this.refreshGeneration;
@@ -1057,14 +1369,12 @@
1057
1369
  }
1058
1370
  }, delayMs);
1059
1371
  }
1060
- async safePublicKey() {
1061
- try {
1062
- return await this.options.getPublicKey();
1063
- }
1064
- catch (error) {
1065
- logger.debug('public key unavailable; entitlement stays unverified', error);
1066
- return null;
1067
- }
1372
+ measureClockSkew(local, server) {
1373
+ const ms = local - server;
1374
+ this.clockSkew =
1375
+ Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
1376
+ ? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
1377
+ : null;
1068
1378
  }
1069
1379
  async discard() {
1070
1380
  this.held = null;
@@ -1074,7 +1384,13 @@
1074
1384
  }
1075
1385
  fingerprint() {
1076
1386
  const state = this.snapshot();
1077
- return canonicalJson({ items: state.items, requiresOnlineCheck: state.requiresOnlineCheck });
1387
+ return canonicalJson({
1388
+ items: state.items,
1389
+ requiresOnlineCheck: state.requiresOnlineCheck,
1390
+ ...(state.regionalFreeUntil
1391
+ ? { regionalFreeUntil: state.regionalFreeUntil, features: state.features }
1392
+ : {}),
1393
+ });
1078
1394
  }
1079
1395
  notifyIfChanged() {
1080
1396
  const fingerprint = this.fingerprint();
@@ -1087,16 +1403,31 @@
1087
1403
  if (!this.held)
1088
1404
  return NaN;
1089
1405
  // fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
1090
- return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + MAX_OFFLINE_AGE_MS;
1406
+ return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
1407
+ }
1408
+ /** The signed allowance of the held license, or 48 hours when it names none. */
1409
+ offlineAgeMs() {
1410
+ const seconds = this.held?.envelope.payload.offlineSeconds;
1411
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
1412
+ return MAX_OFFLINE_AGE_MS;
1413
+ return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
1091
1414
  }
1092
1415
  snapshot() {
1093
1416
  if (!this.held)
1094
- return EMPTY_ENTITLEMENT;
1417
+ return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
1095
1418
  if (this.source !== 'mock' && !this.held.verified) {
1096
- return { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source };
1097
- }
1098
- const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1099
- const hasPaidAccess = collectFeatures(items).length > 0 ||
1419
+ return {
1420
+ ...EMPTY_ENTITLEMENT,
1421
+ requiresOnlineCheck: true,
1422
+ clockSkew: this.clockSkew,
1423
+ source: this.held.source,
1424
+ };
1425
+ }
1426
+ const grants = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1427
+ const regional = grants.find((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU && grant.status === 'active');
1428
+ const items = grants.filter((grant) => grant.sku !== PAY_REGIONAL_ACCESS_SKU);
1429
+ const hasPaidAccess = grants.some((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU) ||
1430
+ collectFeatures(items).length > 0 ||
1100
1431
  items.some((item) => item.status === 'active' || item.status === 'grace');
1101
1432
  const offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline();
1102
1433
  const requiresOnlineCheck = offlineUntil !== null &&
@@ -1106,9 +1437,13 @@
1106
1437
  this.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt));
1107
1438
  return {
1108
1439
  items,
1109
- features: requiresOnlineCheck ? [] : collectFeatures(items),
1440
+ features: requiresOnlineCheck ? [] : collectFeatures(grants),
1441
+ ...(regional?.expiresAt && !requiresOnlineCheck
1442
+ ? { regionalFreeUntil: Date.parse(regional.expiresAt) }
1443
+ : {}),
1110
1444
  requiresOnlineCheck,
1111
1445
  offlineUntil,
1446
+ clockSkew: this.clockSkew,
1112
1447
  verified: this.held.verified,
1113
1448
  issuedAt: this.held.envelope.payload.issuedAt,
1114
1449
  fetchedAt: this.held.fetchedAt,
@@ -1197,6 +1532,16 @@
1197
1532
  this.map.delete(key);
1198
1533
  }
1199
1534
  }
1535
+ /**
1536
+ * The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
1537
+ * only the trial start there (never `endUserRef`), so devices on one synced account share the
1538
+ * trial. Uninstalling clears it from the account, so it does not survive a reinstall.
1539
+ */
1540
+ function createSyncStorage() {
1541
+ const g = extensionGlobals();
1542
+ const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
1543
+ return area ? new ExtensionStorage(area) : null;
1544
+ }
1200
1545
  function createStorage() {
1201
1546
  const g = extensionGlobals();
1202
1547
  const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
@@ -1253,7 +1598,7 @@
1253
1598
  const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
1254
1599
  const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
1255
1600
  const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
1256
- const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
1601
+ const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
1257
1602
  if (!Number.isFinite(Date.parse(created.expiresAt)))
1258
1603
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
1259
1604
  const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
@@ -1313,8 +1658,9 @@
1313
1658
  break;
1314
1659
  if (claim.state === 'complete') {
1315
1660
  const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
1661
+ const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
1316
1662
  await this.options.storage.remove(this.pendingKey);
1317
- return { state: 'complete', entitlement };
1663
+ return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
1318
1664
  }
1319
1665
  if (claim.state !== 'pending')
1320
1666
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
@@ -1460,11 +1806,12 @@
1460
1806
  }
1461
1807
 
1462
1808
  /** Kept in sync with package.json by tests/unit/version.test.ts. */
1463
- const VERSION = '0.9.0';
1809
+ const VERSION = '0.12.0';
1464
1810
 
1465
1811
  const DEFAULT_API_URL = 'https://bff.extenshi.io';
1466
1812
  const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
1467
1813
  const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
1814
+ const DEFAULT_TRIAL_ENDING_DAYS = 2;
1468
1815
 
1469
1816
  const ENVIRONMENTS = new Set(['production', 'sandbox', 'development']);
1470
1817
  const LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug']);
@@ -1492,7 +1839,7 @@
1492
1839
  if (!isHttpUrl(apiUrl))
1493
1840
  errors.push('apiUrl must be an http(s) URL');
1494
1841
  const entitlementPublicKey = input.entitlementPublicKey ?? null;
1495
- if (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {
1842
+ if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
1496
1843
  errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
1497
1844
  }
1498
1845
  const environment = input.environment ?? 'production';
@@ -1514,6 +1861,9 @@
1514
1861
  const theme = input.theme ?? {};
1515
1862
  if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
1516
1863
  errors.push('theme.mode must be light, dark or auto');
1864
+ const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
1865
+ if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
1866
+ errors.push('trialEndingDays must be a whole number of days between 0 and 365');
1517
1867
  if (input.mock &&
1518
1868
  input.mockData !== undefined &&
1519
1869
  (typeof input.mockData !== 'object' || input.mockData === null)) {
@@ -1534,6 +1884,8 @@
1534
1884
  mock: input.mock === true,
1535
1885
  mockData: input.mock ? (input.mockData ?? {}) : null,
1536
1886
  theme,
1887
+ trialEndingDays,
1888
+ syncTrialStart: input.syncTrialStart !== false,
1537
1889
  };
1538
1890
  }
1539
1891
 
@@ -1585,8 +1937,10 @@
1585
1937
  * extends it with `getOffer()` / `showPaywall()`.
1586
1938
  *
1587
1939
  * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
1588
- * `locale` and checkout session IDs. Explicit recovery also sends its session ID,
1589
- * challenge and claim secret (POST body). Email stays on the hosted page.
1940
+ * `locale`, checkout session IDs and, with a server trial, the trial start date
1941
+ * the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
1942
+ * challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
1943
+ * storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
1590
1944
  */
1591
1945
  /** Server-side offer cache is 5 min; mirror it in memory. */
1592
1946
  const OFFER_TTL_MS = 5 * 60 * 1000;
@@ -1597,12 +1951,30 @@
1597
1951
  this.endUserRefPromise = null;
1598
1952
  this.offer = null;
1599
1953
  this.offerInflight = null;
1954
+ /** The signing key the server returned in this session; never one read from storage. */
1955
+ this.serverKey = null;
1956
+ /** Trust order for license signatures; see payment/signature.ts. */
1957
+ this.keys = {
1958
+ known: async () => {
1959
+ const pinned = this.config.entitlementPublicKey;
1960
+ const offline = pinned ?? (await this.readSavedServerKey());
1961
+ return [...new Set([this.serverKey, offline].filter((key) => !!key))];
1962
+ },
1963
+ fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
1964
+ };
1600
1965
  this.readyPromise = null;
1601
1966
  this.destroyed = false;
1602
1967
  this.config = resolveConfig(config);
1603
1968
  logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
1604
1969
  this.now = deps.now ?? (() => Date.now());
1605
1970
  this.storage = deps.storage ?? createStorage();
1971
+ this.openUrl = deps.openUrl;
1972
+ this.syncStorage =
1973
+ !this.config.syncTrialStart || this.config.mock
1974
+ ? null
1975
+ : deps.syncStorage === undefined
1976
+ ? createSyncStorage()
1977
+ : deps.syncStorage;
1606
1978
  const transport = deps.transport ??
1607
1979
  (this.config.mock
1608
1980
  ? new MockTransport(this.config.mockData ?? {})
@@ -1615,11 +1987,29 @@
1615
1987
  cacheTtlMs: this.config.cacheTtlMs,
1616
1988
  source: this.config.mock ? 'mock' : 'network',
1617
1989
  getEndUserRef: () => this.getEndUserRef(),
1618
- getPublicKey: () => this.getPublicKey(),
1990
+ keys: this.keys,
1619
1991
  onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
1992
+ onAccepted: () => {
1993
+ void this.trial.evaluate();
1994
+ void this.rememberTrialStart();
1995
+ },
1996
+ getTrialStartHint: () => this.readTrialStartHint(),
1620
1997
  onError: (error) => this.reportError(error),
1621
1998
  now: this.now,
1622
1999
  });
2000
+ this.trial = new TrialNotifier({
2001
+ storage: this.storage,
2002
+ storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
2003
+ endingDays: this.config.trialEndingDays,
2004
+ getTrial: () => this.entitlements.getTrial(),
2005
+ // A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
2006
+ hasPaidAccess: () => {
2007
+ const license = this.entitlements.getCached();
2008
+ return Boolean(license?.regionalFreeUntil || license?.items.some(isLive));
2009
+ },
2010
+ emit: (event, trial) => this.emitter.emit(event, trial),
2011
+ now: this.now,
2012
+ });
1623
2013
  this.checkout = new CheckoutManager({
1624
2014
  api: this.api,
1625
2015
  storage: this.storage,
@@ -1633,6 +2023,13 @@
1633
2023
  (this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
1634
2024
  now: this.now,
1635
2025
  });
2026
+ this.backup = new CloudBackup({
2027
+ storage: this.storage,
2028
+ publishableKey: this.config.publishableKey,
2029
+ apiUrl: this.config.apiUrl,
2030
+ fetch: deps.fetch,
2031
+ mock: this.config.mock,
2032
+ });
1636
2033
  this.recovery = new RecoveryManager({
1637
2034
  api: this.api,
1638
2035
  locale: this.config.locale,
@@ -1646,7 +2043,7 @@
1646
2043
  envelope.payload.publishableKey !== this.config.publishableKey ||
1647
2044
  !Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
1648
2045
  Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
1649
- (await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid')
2046
+ (await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
1650
2047
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
1651
2048
  this.entitlements.stopAutoRefresh();
1652
2049
  try {
@@ -1664,6 +2061,7 @@
1664
2061
  this.entitlements.startAutoRefresh();
1665
2062
  }
1666
2063
  },
2064
+ onStorageGrant: (grant) => this.backup.accept(grant),
1667
2065
  });
1668
2066
  if (config.onError)
1669
2067
  this.emitter.on('error', config.onError);
@@ -1709,8 +2107,11 @@
1709
2107
  catch (error) {
1710
2108
  this.reportError(error);
1711
2109
  }
1712
- if (!this.destroyed)
2110
+ void this.confirmSavedServerKey();
2111
+ if (!this.destroyed) {
1713
2112
  this.entitlements.startAutoRefresh();
2113
+ this.trial.start();
2114
+ }
1714
2115
  }
1715
2116
  /** The anonymous, random id this install is known by. */
1716
2117
  getEndUserRef() {
@@ -1731,6 +2132,16 @@
1731
2132
  await this.initialize();
1732
2133
  return this.entitlements.get(options);
1733
2134
  }
2135
+ /**
2136
+ * The free trial the application set on the server, from the verified license, or null when
2137
+ * there is none (or the license could not be verified yet). Answers offline from the cached
2138
+ * license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
2139
+ * `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
2140
+ */
2141
+ async getTrial(options = {}) {
2142
+ await this.getEntitlement(options);
2143
+ return this.entitlements.getTrial();
2144
+ }
1734
2145
  /** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
1735
2146
  async isPaid(sku) {
1736
2147
  return isEntitled(await this.getEntitlement(), sku);
@@ -1814,6 +2225,41 @@
1814
2225
  throw this.reportError(error);
1815
2226
  }
1816
2227
  }
2228
+ /**
2229
+ * Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
2230
+ * hosted restore page shows the storage disclosure and the buyer confirms with
2231
+ * the code from the purchase email. `cloudBackup` in the result says whether it is
2232
+ * on. Buyers only; consent is recorded by the server.
2233
+ */
2234
+ enableCloudBackup(options = {}) {
2235
+ return this.restorePurchase({ ...options, purpose: 'storage' });
2236
+ }
2237
+ /**
2238
+ * The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
2239
+ * while cloud backup is off on this installation. Extension pages and background
2240
+ * only: it rejects in a content script, and must never be sent to one.
2241
+ */
2242
+ async cloudBackupToken() {
2243
+ return this.backup.token();
2244
+ }
2245
+ /** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
2246
+ async disableCloudBackup() {
2247
+ try {
2248
+ await this.backup.disable();
2249
+ }
2250
+ catch (error) {
2251
+ throw this.reportError(error);
2252
+ }
2253
+ }
2254
+ /** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
2255
+ async deleteCloudBackup() {
2256
+ try {
2257
+ await this.backup.delete();
2258
+ }
2259
+ catch (error) {
2260
+ throw this.reportError(error);
2261
+ }
2262
+ }
1817
2263
  /** Read-only license view. Entitlements retain cache/signature/offline semantics. */
1818
2264
  async getLicenseSummary(options = {}) {
1819
2265
  await this.initialize();
@@ -1883,6 +2329,7 @@
1883
2329
  destroy() {
1884
2330
  this.destroyed = true;
1885
2331
  this.recovery.stop();
2332
+ this.trial.stop();
1886
2333
  this.entitlements.stopAutoRefresh();
1887
2334
  this.emitter.removeAll();
1888
2335
  }
@@ -1894,8 +2341,9 @@
1894
2341
  if (!this.offerInflight) {
1895
2342
  this.offerInflight = this.api
1896
2343
  .getOffer(this.config.locale)
1897
- .then((value) => {
2344
+ .then(async (value) => {
1898
2345
  this.offer = { value, fetchedAt: this.now() };
2346
+ await this.rememberServerKey(value.entitlementPublicKey);
1899
2347
  return value;
1900
2348
  })
1901
2349
  .finally(() => {
@@ -1904,8 +2352,88 @@
1904
2352
  }
1905
2353
  return this.offerInflight;
1906
2354
  }
1907
- async getPublicKey() {
1908
- return this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey;
2355
+ get serverKeyStorageKey() {
2356
+ return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
2357
+ }
2358
+ async readSavedServerKey() {
2359
+ try {
2360
+ const value = await this.storage.get(this.serverKeyStorageKey);
2361
+ return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
2362
+ }
2363
+ catch {
2364
+ return null;
2365
+ }
2366
+ }
2367
+ /**
2368
+ * Keeps the server's key next to the license cache so a restart with no network can verify it.
2369
+ * Not with a bundled key: that one already covers the restart, and storage stays untrusted.
2370
+ */
2371
+ async rememberServerKey(key) {
2372
+ if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
2373
+ return;
2374
+ this.serverKey = key;
2375
+ if (this.config.entitlementPublicKey || this.config.mock)
2376
+ return;
2377
+ try {
2378
+ if ((await this.readSavedServerKey()) !== key)
2379
+ await this.storage.set(this.serverKeyStorageKey, key);
2380
+ }
2381
+ catch (error) {
2382
+ logger.debug('signing key not saved', error);
2383
+ }
2384
+ }
2385
+ /**
2386
+ * A license verified with the saved key alone is checked against the server once per start:
2387
+ * when the server's key differs (rotation, or an edited storage) the license is fetched again,
2388
+ * and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
2389
+ */
2390
+ async confirmSavedServerKey() {
2391
+ const used = this.entitlements.verifiedKey;
2392
+ if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
2393
+ return;
2394
+ try {
2395
+ if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
2396
+ return;
2397
+ }
2398
+ catch {
2399
+ return;
2400
+ }
2401
+ try {
2402
+ await this.entitlements.refresh();
2403
+ }
2404
+ catch {
2405
+ await this.entitlements.reverify().catch((error) => this.reportError(error));
2406
+ }
2407
+ }
2408
+ get trialStartKey() {
2409
+ return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
2410
+ }
2411
+ /** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
2412
+ async readTrialStartHint() {
2413
+ if (!this.syncStorage)
2414
+ return null;
2415
+ try {
2416
+ const value = await this.syncStorage.get(this.trialStartKey);
2417
+ return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
2418
+ }
2419
+ catch {
2420
+ return null;
2421
+ }
2422
+ }
2423
+ /** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
2424
+ async rememberTrialStart() {
2425
+ const trial = this.entitlements.getTrial();
2426
+ if (!this.syncStorage || !trial)
2427
+ return;
2428
+ try {
2429
+ const synced = await this.readTrialStartHint();
2430
+ if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
2431
+ return;
2432
+ await this.syncStorage.set(this.trialStartKey, trial.startedAt);
2433
+ }
2434
+ catch (error) {
2435
+ logger.debug('trial start not synced', error);
2436
+ }
1909
2437
  }
1910
2438
  reportError(error) {
1911
2439
  const err = ExtenshiPayError.from(error);